import 'dart:convert';

import 'package:flutter_my_app/models/api_response.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:collection/collection.dart'; // 用于 whereIndexed
import 'package:flutter_my_app/models/guangdiu_item.dart';
part 'guangdiu_data.g.dart';

//这个是注解方式生成provider
@riverpod
String helloWorld(Ref ref) {
  return 'Hello world';
}
// 原始数据 Provider（可修改）
@riverpod
class GuangDiuData extends _$GuangDiuData {
  @override
  Future<List<GuangDiuItem>> build() async {
    try {
      final response = await http.get(Uri.https('guangdiu.com', '/api/gethots.php'));
      if (response.statusCode == 200) {
        final json = jsonDecode(response.body) as Map<String, dynamic>;
        final apiResponse = ApiResponse.fromJson(json);
        return apiResponse.data.map((item) => GuangDiuItem(
          id: item.id,
          title: item.title,
          image: item.image,
          ifToBuy: item.ifToBuy,
          buyurl: item.buyurl,
        )).toList();
      } else {
        throw Exception('Failed to load data');
      }
    } catch (e) {
      throw Exception('Error: $e');
    }
  }

  // 添加新项目
  void addItem(GuangDiuItem newItem) async {
    final currentState = await future;
    state = AsyncData([...currentState, newItem]);
  }

  // 删除项目
  void removeItem(int index) async {
    final currentState = await future;
    state = AsyncData(List<GuangDiuItem>.from(currentState)..removeAt(index));
  }
}

// 派生 Provider（自动计算偶数位项目）
@riverpod
Future<List<GuangDiuItem>> evenItems(EvenItemsRef ref) async {
  final items = await ref.watch(guangDiuDataProvider.future);
  return [...items.whereIndexed((index, _) => index.isEven)];
}